package com.cms.acase.proxy

import android.content.ComponentName
import android.content.Intent
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy

/**
 * @author: Mr.You
 * @create: 2023-11-09 15:18
 * @description:
 **/
object ActivityTools {
    const val TARGET_INTENT = "target_intent"


    fun installActivity() {
        //获取ActivityTaskManager 的class
        val activityTaskManagerClass = Class.forName("android.app.ActivityTaskManager")
        //获取ActivityTaskManager的静态属性 IActivityTaskManagerSingleton
        val iActivityTaskManagerSingletonField =
            activityTaskManagerClass.getDeclaredField("IActivityTaskManagerSingleton")
        iActivityTaskManagerSingletonField.isAccessible = true
        //获取IActivityTaskManagerSingleton中的singleton对象
        val singletonInstance = iActivityTaskManagerSingletonField.get(null)

        //获取Singleton的class
        val singletonCLass = Class.forName("android.util.Singleton")
        //获取mInstance 属性
        val mInstanceField = singletonCLass.getDeclaredField("mInstance")
        mInstanceField.isAccessible = true
        //获取get方法
        val getMethod = singletonCLass.getMethod("get")
        //通过get得到 ActivityTaskManager 对象
        val mInstance= getMethod.invoke(singletonInstance)





        val iActivityTaskManagerClass = Class.forName("android.app.IActivityTaskManager")

        val proxy = Proxy.newProxyInstance(Thread.currentThread().contextClassLoader, arrayOf(iActivityTaskManagerClass)
        ,
        InvocationHandler{ _, method, args ->
            if (method.name.equals("startActivity")) {
                var mIndex = -1
                args.forEachIndexed { index, any ->
                    if (any is Intent) {
                        mIndex = index
                    }
                }
                val newIntent = Intent()
                newIntent.component = ComponentName("com.cms.acase.proxy", "com.cms.acase.proxy.TargetActivity")
                val targetIntent = args[mIndex] as Intent
                newIntent.putExtra(TARGET_INTENT,targetIntent)
                args[mIndex] = newIntent

            }
            return@InvocationHandler method.invoke(mInstance,args)

        });
        mInstanceField.set(singletonInstance,proxy)



    }

}